from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field, field_validator
from datetime import date, datetime
import re


class StaffNameValidationError(Exception):
    """员工姓名验证错误异常类"""
    pass


class WorkHoursQueryRequest(BaseModel):
    """工时查询请求模型"""
    people_name: Optional[str] = Field(None, description="员工姓名")
    framework_name: Optional[str] = Field(None, description="部门名称")
    project_id: Optional[str] = Field(None, description="项目ID")
    start_date: Optional[str] = Field(None, description="开始日期 (YYYY-MM-DD)")
    end_date: Optional[str] = Field(None, description="结束日期 (YYYY-MM-DD)")
    
    @field_validator('people_name')
    @classmethod
    def validate_people_name(cls, v):
        """验证员工姓名，只允许中文、英文和数字，不允许特殊符号"""
        if v is None:
            return v
        
        # 正则表达式：只允许中文、英文字母和数字
        pattern = r'^[\u4e00-\u9fff a-zA-Z0-9]+$'
        
        if not re.match(pattern, v):
            raise ValueError(f"员工姓名包含特殊符号。只允许中文、英文和数字。")
        
        return v

    @field_validator('start_date', 'end_date')
    @classmethod
    def validate_dates(cls, v):
        """验证日期格式"""
        if v is None:
            return v
        
        try:
            datetime.strptime(v, '%Y-%m-%d')
            return v
        except ValueError:
            raise ValueError("日期格式错误，请使用 YYYY-MM-DD 格式")
            
    class Config:
        example = {
            "people_name": "张三",
            "framework_name": "技术部",
            "project_id": "PROJ001",
            "start_date": "2024-01-01",
            "end_date": "2024-01-31"
        }


class WorkLogDetail(BaseModel):
    """工时日志详情模型"""
    PeopleName: str
    LogText: str
    WorkHourType: str
    WorkHour: float
    LogTime: datetime
    ProjectName: Optional[str] = None
    FrameworkName: Optional[str] = None
    
    class Config:
        from_attributes = True


class WorkHoursReportResponse(BaseModel):
    """工时报告响应模型"""
    summary: str = Field(..., description="AI 生成的工时总结")
    total_hours: float = Field(..., description="总工时")
    total_records: int = Field(..., description="总记录数")
    details: List[WorkLogDetail] = Field(..., description="详细日志列表")
    
    class Config:
        example = {
            "summary": "本月张三共工作160小时，主要在项目A上投入了60%的时间...",
            "total_hours": 160.0,
            "total_records": 32,
            "details": []
        }


class PeopleInfo(BaseModel):
    """员工信息模型"""
    id: int
    PeopleName: str
    FrameworkId: int
    PersonnelLevel: Optional[str] = None
    FrameworkName: Optional[str] = None
    
    class Config:
        from_attributes = True


class FrameworkInfo(BaseModel):
    """部门信息模型"""
    id: int
    FrameworkName: str
    
    class Config:
        from_attributes = True


class ProjectInfo(BaseModel):
    """项目信息模型"""
    Id: int
    ProjectId: str
    ProjectName: str
    ProjectType: Optional[str] = None
    Project: Optional[str] = None
    CreateTime: Optional[datetime] = None
    
    class Config:
        from_attributes = True


class PeopleWorkHoursResponse(BaseModel):
    """员工工时响应模型"""
    people_name: str
    framework_name: Optional[str] = None
    total_hours: float
    work_logs: List[WorkLogDetail]
    
    class Config:
        example = {
            "people_name": "张三",
            "framework_name": "技术部",
            "total_hours": 160.0,
            "work_logs": []
        }


class FrameworkWorkHoursResponse(BaseModel):
    """部门工时响应模型"""
    framework_name: str
    total_hours: float
    total_people: int
    work_logs: List[WorkLogDetail]
    
    class Config:
        example = {
            "framework_name": "技术部",
            "total_hours": 800.0,
            "total_people": 5,
            "work_logs": []
        }


class ProjectWorkHoursResponse(BaseModel):
    """项目工时响应模型"""
    project_id: str
    project_name: str
    total_hours: float
    total_people: int
    work_logs: List[WorkLogDetail]
    
    class Config:
        example = {
            "project_id": "PROJ001",
            "project_name": "牛马工时系统",
            "total_hours": 500.0,
            "total_people": 3,
            "work_logs": []
        }


class ApiResponse(BaseModel):
    """通用 API 响应模型"""
    code: int = Field(..., description="响应状态码")
    message: str = Field(..., description="响应消息")
    data: Optional[Any] = Field(None, description="响应数据")
    
    class Config:
        example = {
            "code": 200,
            "message": "查询成功",
            "data": {}
        }


class ErrorResponse(BaseModel):
    """错误响应模型"""
    code: int = Field(..., description="错误状态码")
    message: str = Field(..., description="错误消息")
    detail: Optional[str] = Field(None, description="错误详情")
    
    class Config:
        example = {
            "code": 400,
            "message": "参数错误",
            "detail": "员工姓名不能为空"
        }


class HealthResponse(BaseModel):
    """健康检查响应模型"""
    status: str = Field(..., description="服务状态")
    timestamp: datetime = Field(..., description="检查时间")
    database_connected: bool = Field(..., description="数据库连接状态")
    
    class Config:
        example = {
            "status": "healthy",
            "timestamp": "2024-01-01T12:00:00",
            "database_connected": True
        }


class AIReportRequest(BaseModel):
    """AI报告生成请求模型"""
    people_name: Optional[str] = Field(None, description="员工姓名")
    framework_name: Optional[str] = Field(None, description="部门名称")
    project_id: Optional[str] = Field(None, description="项目ID")
    start_date: Optional[str] = Field(None, description="开始日期 (YYYY-MM-DD)")
    end_date: Optional[str] = Field(None, description="结束日期 (YYYY-MM-DD)")
    report_type: str = Field("markdown", description="报告类型: html 或 markdown")
    # include_details: bool = Field(True, description="是否包含详细分析")
    # include_recommendations: bool = Field(True, description="是否包含改进建议")
    
    @field_validator('report_type')
    @classmethod
    def validate_report_type(cls, v):
        """验证报告类型"""
        if v not in ["html", "markdown"]:
            raise ValueError("报告类型必须是 'html' 或 'markdown'")
        return v
    
    @field_validator('people_name')
    @classmethod
    def validate_people_name(cls, v):
        """验证员工姓名，只允许中文、英文和数字，不允许特殊符号"""
        if v is None:
            return v
        
        # 正则表达式：只允许中文、英文字母和数字
        pattern = r'^[\u4e00-\u9fff a-zA-Z0-9]+$'
        
        if not re.match(pattern, v):
            raise ValueError("员工姓名包含特殊符号。只允许中文、英文和数字。")
        
        return v

    @field_validator('start_date', 'end_date')
    @classmethod
    def validate_dates(cls, v):
        """验证日期格式"""
        if v is None:
            return v
        
        try:
            datetime.strptime(v, '%Y-%m-%d')
            return v
        except ValueError:
            raise ValueError("日期格式错误，请使用 YYYY-MM-DD 格式")
    
    class Config:
        example = {
            "people_name": "BAI HAO",
            "framework_name": "AGI部",
            "project_id": "1-PLP-029-A",
            "start_date": "2025-03-01",
            "end_date": "2025-03-31",
            "report_type": "markdown",
            # "include_details": True,
            # "include_recommendations": True
        }


class AIReportResponse(BaseModel):
    """AI报告响应模型"""
    report_type: str = Field(..., description="报告类型")
    content: str = Field(..., description="AI生成的报告内容")
    statistics: Dict[str, Any] = Field(..., description="统计信息")
    query_params: Dict[str, Any] = Field(..., description="查询参数")
    generated_at: str = Field(..., description="生成时间")
    
    class Config:
        example = {
            "report_type": "markdown",
            "content": "# 🐂 牛马工时报告\n\n## 📊 统计信息...",
            "statistics": {
                "total_hours": 208.5,
                "total_records": 33,
                "generated_at": "2025-07-03T11:52:31.346190"
            },
            "query_params": {
                "people_name": "白昊",
                "start_date": "2025-03-01",
                "end_date": "2025-03-31"
            },
            "generated_at": "2025-07-03T11:52:31"
        }


class AIServiceStatus(BaseModel):
    """AI服务状态模型"""
    enabled: bool = Field(..., description="AI服务是否启用")
    model: str = Field(..., description="使用的AI模型")
    api_available: bool = Field(..., description="API是否可用")
    last_check: str = Field(..., description="最后检查时间")
    
    class Config:
        example = {
            "enabled": True,
            "model": "deepseek-ai/DeepSeek-V3",
            "api_available": True,
            "last_check": "2025-07-03T11:52:31"
        } 